#include "ChatterBoxServer.h"

#include <QTcpSocket>
#include <QRegExp>
#include <QFile>
#include <QDateTime>

#include <assert.h>

ChatterBoxServer::ChatterBoxServer(QObject *parent) : QTcpServer(parent)
{
	m_pLogFile = new QFile("/home/"+QString(getenv("USER"))+"/memuSoftChatLog.txt");
	assert(m_pLogFile->open(QIODevice::Append | QIODevice::Text));
	m_pLog = new QTextStream(m_pLogFile);
}

ChatterBoxServer::~ChatterBoxServer()
{
	delete m_pLog;
}

void ChatterBoxServer::incomingConnection(int socketfd)
{
	QTcpSocket *client = new QTcpSocket(this);
	client->setSocketDescriptor(socketfd);
	clients.insert(client);

	qDebug() << "New client from:" << client->peerAddress().toString();
	log("New client from:" + client->peerAddress().toString() + "\n");

	connect(client, SIGNAL(readyRead()), this, SLOT(readyRead()));
	connect(client, SIGNAL(disconnected()), this, SLOT(disconnected()));
}

void ChatterBoxServer::readyRead()
{
	QTcpSocket *client = (QTcpSocket*)sender();
	while(client->canReadLine())
	{
		QString line = QString::fromUtf8(client->readLine()).trimmed();
		qDebug() << "Read line:" << line;

		QRegExp meRegex("^/me:(.*)$");

		if(meRegex.indexIn(line) != -1)
		{
			QString user = meRegex.cap(1);
			users[client] = user;
			foreach(QTcpSocket *client, clients)
				client->write(QString("Server:" + user + " has joined.\n").toUtf8());
			sendUserList();
		}
		else if(users.contains(client))
		{
			QString message = line;
			QString user = users[client];

			qDebug() << "User:" << user;
			qDebug() << "Message:" << message;

			log(QString(user + ":" + message + "\n"));

			foreach(QTcpSocket *otherClient, clients)
				otherClient->write(QString(user + ":" + message + "\n").toUtf8());
		}
		else
		{
			qWarning() << "Got bad message from client:" << client->peerAddress().toString() << line;
		}
	}
}

void ChatterBoxServer::disconnected()
{
	QTcpSocket *client = (QTcpSocket*)sender();
	qDebug() << "Client disconnected:" << client->peerAddress().toString();
	log("Client disconnected:" + client->peerAddress().toString()+"\n");

	clients.remove(client);

	QString user = users[client];
	users.remove(client);

	sendUserList();
	foreach(QTcpSocket *client, clients)
		client->write(QString("Server:" + user + " has left.\n").toUtf8());
}

void ChatterBoxServer::sendUserList()
{
	QStringList userList;
	foreach(QString user, users.values())
		userList << user;

	foreach(QTcpSocket *client, clients)
		client->write(QString("/users:" + userList.join(",") + "\n").toUtf8());
}

void ChatterBoxServer::log(const QString& event)
{
	(*m_pLog) << QDateTime::currentDateTime().toString("dd/MM/yyyy hh:mm:ss") << ": " << event;
	m_pLog->flush();
}
